<?php
/**
 * (微信端首页在用，其他，放到登录页了！)
 * 语言的切换
 *
 * Author: lyun
 * Date: 2018/5/31
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\Common;

use App\Http\Controllers\ApiController;
use App\Http\Requests\SwitchLanguageRequest;
use App\Models\Admin\CustomerAdmin;
use App\Models\Admin\PanxAdmin;
use App\Models\Admin\StoreAdmin;
use App\Models\Customer\DeviceAccount;
use App\Models\OpenWechat\WechatUser;
use App\Services\Locale\Language;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class SwitchLanguageController extends ApiController
{
    /**
     * @param SwitchLanguageRequest $request
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function switchLanguage(SwitchLanguageRequest $request)
    {
        $type = $request->type;

        switch($type)
        {
            case 'panx':
                $data = $this->setAdminLanguage($request, PanxAdmin::class);
                break;
            case 'customer':
                $data = $this->setAdminLanguage($request, CustomerAdmin::class);
                break;
            case 'store':
                $data = $this->setAdminLanguage($request, StoreAdmin::class);
                break;
            case 'app':
                $data = $this->setAdminLanguage($request, DeviceAccount::class);
                break;
            case 'wechat':
                $data = $this->setAdminLanguage($request, WechatUser::class);
                break;
            default:
                $data = false;
        }

        return $this->response(compact('data'));
    }

    /**
     * @param SwitchLanguageRequest $request
     * @param string $model
     * @return mixed
     * @throws \Exception
     */
    private function setAdminLanguage(SwitchLanguageRequest $request, string $model): bool
    {
        /** @var PanxAdmin|CustomerAdmin|DeviceAccount|StoreAdmin|WechatUser $adminModel */
        $adminModel = (new $model);

        /** @var PanxAdmin|CustomerAdmin|DeviceAccount|StoreAdmin|WechatUser|null $admin */
        $admin = $adminModel->find($request->id);
            $this->checkItemExist($admin, trans('common.language'));

        $language = $this->assembleLanguage($request->language);

        $updated = $admin->update($language);

        return $updated;
    }

    /**
     * @param $language
     * @return array
     */
    private function assembleLanguage($language)
    {
        return ['language' => Language::normalizeLanguageCode($language)];
    }

}
